#pragma once

#include <iostream>
#include <cstring>
#include <strings.h>
#include <string>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace Server
{
    using namespace std;

    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        OPEN_ERR
    };

    typedef function<void(int, string, uint16_t, string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t &cb, const uint16_t &port, const string &ip = defaultIp)
            : _sockfd(-1), _port(port), _callback(cb), _ip(ip)
        {
        }

        void initServer()
        {
            // 1. 创建socket来通信
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "sockfd error: " << errno << " : " << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            cout << "socket success: " << _sockfd << endl;

            // 2. bind
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = inet_addr(_ip.c_str());
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "bind error: " << errno << " : " << strerror(errno) << endl;
                exit(BIND_ERR);
            }
        }

        void start()
        {
            // char buffer[1024];
            char buffer[gnum];
            while (true)
            {
                // 读取数据
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                // 上面的 recvfrom 函数的返回值应该是 buffer 的长度
                if (s > 0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer;

                    cout << clientip << "[" << clientport << "]#" << message << endl;
                    _callback(_sockfd, clientip, clientport, message);
                }
            }
        }

        ~udpServer() {}

    private:
        int _sockfd;
        string _ip; // 实际上，一款网络服务器，不建议指明一个IP
        uint16_t _port;
        func_t _callback; // 回调函数
    };
}
